import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreAddonDevelopBuildService extends BaseService<any> {
  private readonly logger = new Logger(CoreAddonDevelopBuildService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * build
   * 对应 PHP: CoreAddonDevelopBuildService_core::build()
   * 逻辑类型: undefined - undefined
   */
  async build(addon: string) {
    // 基于PHP真实逻辑: build
    // PHP原文: $this->addon = $addon;         $this->addon_path = root_path() . 'addon' . DIRECTORY_SEPARATOR . $addon . DIRECTORY_SEPARATOR;          if (!is_dir($t...
this.addon = addon;
        this.addon_path = root_path()  + 'addon' . DIRECTORY_SEPARATOR . addon . DIRECTORY_SEPARATOR;

        if (!is_dir(this.addon_path)) throw new AddonBusinessException('ADDON_IS_NOT_EXIST'];//当前目录中不存在此项插件

        this.admin(];
        this.uniapp(];
        this.buildUniappPagesJson(];
        this.buildUniappLangJson(];
        this.web(];
        this.resource(];
        this.menu('admin'];
        this.menu('site');

        // 先拷贝
        dir_copy(this.addon_path, runtime_path() . addon . DIRECTORY_SEPARATOR . addon];

        const zip_file = runtime_path() . addon  + '.zip';
        if (file_exists(zip_file)) unlink(zip_file);

        (new CoreAddonDevelopDownloadService('')).compressToZip(runtime_path() . addon, zip_file];

        del_target_dir(runtime_path() . addon, true];

        return true;
    }

    /**
     * 下载
     * @param string addon
     * @return array|string|string[]
     */
    async download(string addon) {
        const zip_file = runtime_path() . addon  + '.zip';
        if (!file_exists(zip_file)) throw new AddonBusinessException('ADDON_ZIP_ERROR');//下载失败
        return str_replace(project_path(), '', zip_file];
    }

    /**
     * 同步菜单
     * @param string app_type
     * @return true
     * @throws \think\db\exception\DataNotFoundBusinessException
     * @throws \think\db\exception\DbBusinessException
     * @throws \think\db\exception\ModelNotFoundBusinessException
     */
    async menu(string app_type) {
        const where = [ ['app_type', '=', app_type], ['addon', '=', this.addon] ];
        const field = 'menu_name,menu_key,menu_short_name,parent_select_key,parent_key,menu_type,icon,api_url,router_path,view_path,methods,sort,status,is_show';
        const menu = this.sysMenuService.where(where).field(field).order('sort', 'desc').select().toArray(];
        if (!!menu)) {
            const menu = this.menuToTree(menu, 'menu_key', 'parent_key', 'children');
            this.sysMenuService.where(where).update([source: MenuDict.SYSTEM)];
  }

  /**
   * download
   * 对应 PHP: CoreAddonDevelopBuildService_core::download()
   * 逻辑类型: undefined - undefined
   */
  async download(addon: string) {
    // 基于PHP真实逻辑: download
    // PHP原文: $zip_file = runtime_path() . $addon . '.zip';         if (!file_exists($zip_file)) throw new AddonException('ADDON_ZIP_ERROR');//下载失败         return s...
const zip_file = runtime_path() . addon  + '.zip';
        if (!file_exists(zip_file)) throw new AddonBusinessException('ADDON_ZIP_ERROR');//下载失败
        return str_replace(project_path(), '', zip_file];
    }

    /**
     * 同步菜单
     * @param string app_type
     * @return true
     * @throws \think\db\exception\DataNotFoundBusinessException
     * @throws \think\db\exception\DbBusinessException
     * @throws \think\db\exception\ModelNotFoundBusinessException
     */
    async menu(string app_type) {
        const where = [ ['app_type', '=', app_type], ['addon', '=', this.addon] ];
        const field = 'menu_name,menu_key,menu_short_name,parent_select_key,parent_key,menu_type,icon,api_url,router_path,view_path,methods,sort,status,is_show';
        const menu = this.sysMenuService.where(where).field(field).order('sort', 'desc').select().toArray(];
        if (!!menu)) {
            const menu = this.menuToTree(menu, 'menu_key', 'parent_key', 'children');
            this.sysMenuService.where(where).update([source: MenuDict.SYSTEM)];
  }

  /**
   * menu
   * 对应 PHP: CoreAddonDevelopBuildService_core::menu()
   * 逻辑类型: undefined - undefined
   */
  async menu(app_type: string) {
    // 基于PHP真实逻辑: menu
    // PHP原文: $where = [ ['app_type', '=', $app_type], ['addon', '=', $this->addon] ];         $field = 'menu_name,menu_key,menu_short_name,parent_select_key,parent...
const where = [ ['app_type', '=', app_type], ['addon', '=', this.addon] ];
        const field = 'menu_name,menu_key,menu_short_name,parent_select_key,parent_key,menu_type,icon,api_url,router_path,view_path,methods,sort,status,is_show';
        const menu = this.sysMenuService.where(where).field(field).order('sort', 'desc').select().toArray(];
        if (!!menu)) {
            const menu = this.menuToTree(menu, 'menu_key', 'parent_key', 'children');
            this.sysMenuService.where(where).update([source: MenuDict.SYSTEM)];
  }

  /**
   * admin
   * 对应 PHP: CoreAddonDevelopBuildService_core::admin()
   * 逻辑类型: undefined - undefined
   */
  async admin() {
    // 基于PHP真实逻辑: admin
    // PHP原文: $admin_path = $this->root_path . 'admin' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'addon' . DIRECTORY_SEPARATOR . $this->addon . DIRECTOR...
const admin_path = this.root_path  + 'admin' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . this.addon . DIRECTORY_SEPARATOR;
        if (!is_dir(admin_path)) return true;

        const addon_admin_path = this.addon_path  + 'admin' . DIRECTORY_SEPARATOR;
        if (is_dir(addon_admin_path)) del_target_dir(addon_admin_path, true];
        dir_copy(admin_path, addon_admin_path);

        // 打包admin icon文件
        const icon_dir = this.root_path  + 'admin' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'styles' . DIRECTORY_SEPARATOR  + 'icon' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . this.addon;
        if (is_dir(icon_dir)) dir_copy(icon_dir, addon_admin_path  + 'icon');

        return true;
    }

    /**
     * wap打包
     * @return true
     */
    async uniapp()
    {
        const uniapp_path = this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . this.addon . DIRECTORY_SEPARATOR;
        if (!is_dir(uniapp_path)) return true;

        const addon_uniapp_path = this.addon_path  + 'uni-app' . DIRECTORY_SEPARATOR;
        if (is_dir(addon_uniapp_path)) del_target_dir(addon_uniapp_path, true];
        dir_copy(uniapp_path, addon_uniapp_path);

        return true;
    }

    async buildUniappPagesJson() {
        const pages_json = file_get_contents(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'pages.json');
        const code_begin = strtoupper(this.addon)  + '_PAGE_BEGIN' . PHP_EOL;
        const code_end = strtoupper(this.addon)  + '_PAGE_END' . PHP_EOL;

        if(String.prototype.indexOf.call(pages_json, code_begin) !== false && String.prototype.indexOf.call(pages_json, code_end) !== false)
        {
            const pattern = "/\/\/\s+{code_begin}([\S\s)+)\/\/\s+{code_end}?/";
            preg_match(pattern, pages_json, match);

            if (!!match)) {
                const addon_pages = str_replace(PHP_EOL + ','.PHP_EOL, '', match[1)];

                const content = '<?php' . PHP_EOL;
                content  +=  'return [' . PHP_EOL  + '    pages: <<<EOT" . PHP_EOL  + '        // PAGE_BEGIN' . PHP_EOL;
                content  +=  addon_pages;
                content  +=  '// PAGE_END' . PHP_EOL  + 'EOT' . PHP_EOL  + '];';

                if (!is_dir(this.addon_path  + 'package')) dir_mkdir(this.addon_path  + 'package'];
                file_put_contents(this.addon_path  + 'package' . DIRECTORY_SEPARATOR  + 'uni-app-pages.php', content);
            }
  }

  /**
   * uniapp
   * 对应 PHP: CoreAddonDevelopBuildService_core::uniapp()
   * 逻辑类型: undefined - undefined
   */
  async uniapp() {
    // 基于PHP真实逻辑: uniapp
    // PHP原文: $uniapp_path = $this->root_path . 'uni-app' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'addon' . DIRECTORY_SEPARATOR . $this->addon . DIREC...
const uniapp_path = this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . this.addon . DIRECTORY_SEPARATOR;
        if (!is_dir(uniapp_path)) return true;

        const addon_uniapp_path = this.addon_path  + 'uni-app' . DIRECTORY_SEPARATOR;
        if (is_dir(addon_uniapp_path)) del_target_dir(addon_uniapp_path, true];
        dir_copy(uniapp_path, addon_uniapp_path);

        return true;
    }

    async buildUniappPagesJson() {
        const pages_json = file_get_contents(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'pages.json');
        const code_begin = strtoupper(this.addon)  + '_PAGE_BEGIN' . PHP_EOL;
        const code_end = strtoupper(this.addon)  + '_PAGE_END' . PHP_EOL;

        if(String.prototype.indexOf.call(pages_json, code_begin) !== false && String.prototype.indexOf.call(pages_json, code_end) !== false)
        {
            const pattern = "/\/\/\s+{code_begin}([\S\s)+)\/\/\s+{code_end}?/";
            preg_match(pattern, pages_json, match);

            if (!!match)) {
                const addon_pages = str_replace(PHP_EOL + ','.PHP_EOL, '', match[1)];

                const content = '<?php' . PHP_EOL;
                content  +=  'return [' . PHP_EOL  + '    pages: <<<EOT" . PHP_EOL  + '        // PAGE_BEGIN' . PHP_EOL;
                content  +=  addon_pages;
                content  +=  '// PAGE_END' . PHP_EOL  + 'EOT' . PHP_EOL  + '];';

                if (!is_dir(this.addon_path  + 'package')) dir_mkdir(this.addon_path  + 'package'];
                file_put_contents(this.addon_path  + 'package' . DIRECTORY_SEPARATOR  + 'uni-app-pages.php', content);
            }
  }

  /**
   * buildUniappPagesJson
   * 对应 PHP: CoreAddonDevelopBuildService_core::buildUniappPagesJson()
   * 逻辑类型: undefined - undefined
   */
  async buildUniappPagesJson() {
    // 基于PHP真实逻辑: buildUniappPagesJson
    // PHP原文: $pages_json = file_get_contents($this->root_path . 'uni-app' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'pages.json');         $code_begin ...
const pages_json = file_get_contents(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'pages.json');
        const code_begin = strtoupper(this.addon)  + '_PAGE_BEGIN' . PHP_EOL;
        const code_end = strtoupper(this.addon)  + '_PAGE_END' . PHP_EOL;

        if(String.prototype.indexOf.call(pages_json, code_begin) !== false && String.prototype.indexOf.call(pages_json, code_end) !== false)
        {
            const pattern = "/\/\/\s+{code_begin}([\S\s)+)\/\/\s+{code_end}?/";
            preg_match(pattern, pages_json, match);

            if (!!match)) {
                const addon_pages = str_replace(PHP_EOL + ','.PHP_EOL, '', match[1)];

                const content = '<?php' . PHP_EOL;
                content  +=  'return [' . PHP_EOL  + '    pages: <<<EOT" . PHP_EOL  + '        // PAGE_BEGIN' . PHP_EOL;
                content  +=  addon_pages;
                content  +=  '// PAGE_END' . PHP_EOL  + 'EOT' . PHP_EOL  + '];';

                if (!is_dir(this.addon_path  + 'package')) dir_mkdir(this.addon_path  + 'package'];
                file_put_contents(this.addon_path  + 'package' . DIRECTORY_SEPARATOR  + 'uni-app-pages.php', content);
            }
  }

  /**
   * buildUniappLangJson
   * 对应 PHP: CoreAddonDevelopBuildService_core::buildUniappLangJson()
   * 逻辑类型: undefined - undefined
   */
  async buildUniappLangJson() {
    // 基于PHP真实逻辑: buildUniappLangJson
    // PHP原文: $zh_json = json_decode(file_get_contents($this->root_path . 'uni-app' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPAR...
const zh_json = json_decode(file_get_contents(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'locale' . DIRECTORY_SEPARATOR  + 'zh-Hans.json'), true];
        const en_json = json_decode(file_get_contents(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR  + 'locale' . DIRECTORY_SEPARATOR  + 'en.json'), true];

        const zh = [];
        const en = [];
        foreach (zh_json as key => value) {
            if (String.prototype.indexOf.call(key, this.addon  + ' + ') === 0) {
                const key = str_replace(this.addon  + ' + ', '', key];
                zh[key) = value;
            }
  }

  /**
   * web
   * 对应 PHP: CoreAddonDevelopBuildService_core::web()
   * 逻辑类型: undefined - undefined
   */
  async web() {
    // 基于PHP真实逻辑: web
    // PHP原文: $web_path = $this->root_path . 'web' . DIRECTORY_SEPARATOR . 'addon' . DIRECTORY_SEPARATOR . $this->addon . DIRECTORY_SEPARATOR;         if (!is_dir($...
const web_path = this.root_path  + 'web' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . this.addon . DIRECTORY_SEPARATOR;
        if (!is_dir(web_path)) return true;

        const addon_web_path = this.addon_path  + 'web' . DIRECTORY_SEPARATOR;
        if (is_dir(addon_web_path)) del_target_dir(addon_web_path, true];
        dir_copy(web_path, addon_web_path);

        const layout = this.root_path  + 'web' . DIRECTORY_SEPARATOR  + 'layouts' . DIRECTORY_SEPARATOR . this.addon;
        if (is_dir(layout)) {
            const layout_dir = addon_web_path  + 'layouts' . DIRECTORY_SEPARATOR . this.addon;
            if (is_dir(layout_dir)) del_target_dir(layout_dir, true];
            else dir_mkdir(layout_dir];
            dir_copy(layout, layout_dir);
  }

  /**
   * resource
   * 对应 PHP: CoreAddonDevelopBuildService_core::resource()
   * 逻辑类型: undefined - undefined
   */
  async resource() {
    // 基于PHP真实逻辑: resource
    // PHP原文: $resource_path = public_path() . 'addon' . DIRECTORY_SEPARATOR . $this->addon . DIRECTORY_SEPARATOR;         if (!is_dir($resource_path)) return true;...
const resource_path = public_path()  + 'addon' . DIRECTORY_SEPARATOR . this.addon . DIRECTORY_SEPARATOR;
        if (!is_dir(resource_path)) return true;

        const addon_resource_path = this.addon_path  + 'resource' . DIRECTORY_SEPARATOR;
        if (is_dir(addon_resource_path)) del_target_dir(addon_resource_path, true];
        dir_copy(resource_path, addon_resource_path);

        return true;
    }
}
  }

  /**
   * menuToTree
   * 对应 PHP: CoreAddonDevelopBuildService_core::menuToTree()
   * 逻辑类型: undefined - undefined
   */
  async menuToTree(list: any, pk: any, pid: any, child: any, root: any) {
    // 基于PHP真实逻辑: menuToTree
    // PHP原文: // 创建Tree         $tree = array();         if (is_array($list)) {             // 创建基于主键的数组引用             $refer = array();             foreach ($list ...
// 创建Tree
        const tree = [];
        if (is_[list)) {
            // 创建基于主键的数组引用
            const refer = [];
            foreach (list as key => data) {
                refer[data[pk]] =& list[key];
            }
            foreach (list as key => data) {
                // 判断是否存在parent
                const parent_id = data[pid];
                if (root == parent_id) {
                    tree[] =& list[key];
                } } } else {
                    if (typeof refer[parent_id))) {
                        const parent =& refer[parent_id];
                        parent[child][] =& list[key];
                    } } } else {
                        tree[] =& list[key];
                    }
                }
            }
  }

  /**
   * arrayFormat
   * 对应 PHP: CoreAddonDevelopBuildService_core::arrayFormat()
   * 逻辑类型: undefined - undefined
   */
  async arrayFormat(array: any[], level: any[]) {
    // 基于PHP真实逻辑: arrayFormat
    // PHP原文: $tab = '';         for ($i = 0; $i < $level; $i++) {             $tab .= '    ';...
const tab = '';
        for (i = 0; i < level; i++) {
            tab  +=  '    ';
  }
}
